/*
 * @Description: 
 * @Author: HuRrongChao
 * @Date: 2025-01-09 15:47:41
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-01-09 15:54:01
 */
import { ref, nextTick } from 'vue'
/**
 * @method 初始化
 * @param containerRef 容器
 * @param cutBoxRef 裁剪框
 * @returns
 */
export function useInit(containerRef, cutBoxRef, imgRef, currentTop, currentLeft) {
  const imgWdith = ref(0) // 图片宽
  const imgHeight = ref(0) // 图片高
  const zoom = ref(1) // 缩放倍数

  // 适应大小居中
  const resizeCutBox = () => {
    const container = containerRef.value
    const dom = cutBoxRef.value
    const w = container.offsetWidth
    const h = container.offsetHeight
    const dw = dom.offsetWidth
    const dh = dom.offsetHeight
    currentLeft.value = (w - dw) / 2
    currentTop.value = (h - dh) / 2
  }

  // 初始化容器和图片宽高
  const initContainer = (e) => {
    const iw = imgRef.value.naturalWidth  // 图片宽度
    const ih = imgRef.value.naturalHeight // 图片高度
    const { width: containerWidth, height: containerHeight } = containerRef.value.getBoundingClientRect()

    const imgAspectRatio = iw / ih // 图片的宽高比
    const containerAspectRatio = containerWidth / containerHeight // 容器的宽高比

    let newWidth, newHeight

    if (imgAspectRatio > containerAspectRatio) {
      // 图片宽高比大于容器宽高比，以容器宽度为基准
      newWidth = containerWidth
      newHeight = containerWidth / imgAspectRatio
    } else {
      // 图片宽高比小于等于容器宽高比，以容器高度为基准
      newHeight = containerHeight
      newWidth = containerHeight * imgAspectRatio
    }

    // 计算缩放倍数
    zoom.value = newWidth / iw

    // 对图片和容器进行重置
    imgWdith.value = newWidth
    imgHeight.value = newHeight
    containerRef.value.style.width = newWidth + 'px'
    containerRef.value.style.height = newHeight + 'px'

    // 为了让裁剪框居中，可以一开始铺满，然后用变形缩小，防止后面移动计算top等值的不便--%或px转化不便
    nextTick(resizeCutBox)
  }

  // 百分比转为px,并且去除px
  const translatePX = (widthP, heightP) => {
    const dom = document.createElement('div')
    dom.style.width = widthP
    dom.style.height = heightP
    const container = containerRef.value
    container.appendChild(dom)
    const width = dom.offsetWidth
    const height = dom.offsetHeight
    container.removeChild(dom)
    return {
      width,
      height
    }
  }

  return {
    imgWdith,
    imgHeight,
    zoom,
    resizeCutBox,
    initContainer,
    translatePX
  }
}